/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mytransaction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;

/**
 * references : http://www.java2s.com/Code/Java/Database-SQL-JDBC/UsingadatabasetransactionwithJDBC.htm
 * @author Administrator
 */
public class RollbackDemo {

    Connection connection;

    /**
     * get a connection
     */
    public RollbackDemo() {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
            connection = DriverManager.getConnection("jdbc:sqlserver://dragon;instanceName=sqlexpress;databaseName=for_transaction", "sa", "sol");
        } catch (Exception e) {
            System.err.println("Unable to find and load driver");
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void doWork() {
        try {
            connection.setAutoCommit(false);
            Statement statement = connection.createStatement();

            statement.executeUpdate("insert into comment ([id],[comment],[name]) values "
                    + "('" + UUID.randomUUID() + "','" + UUID.randomUUID() + "','tuan')");

            // raise a sql error for testing rollback
            statement.executeUpdate("insert into comment ([id],[comment],[name]) values "
                    + "('" + UUID.randomUUID() + "','" + UUID.randomUUID() + "','nhutuan')");

            connection.commit();
        } catch (Exception e) {
            try {
                connection.rollback();
                System.out.println("database was rolbacked");
            } catch (SQLException error) {
            }
            e.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        RollbackDemo trans = new RollbackDemo();
        trans.doWork();
    }
}
